package org.jeecg.modules.achexaminationpaper.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.achachievementstandard.entity.AchAchievementStandard;
import org.jeecg.modules.achachievementstandard.service.IAchAchievementStandardService;
import org.jeecg.modules.achachievestandarditem.entity.AchAchieveStandardItem;
import org.jeecg.modules.achachievestandarditem.service.IAchAchieveStandardItemService;
import org.jeecg.modules.achexaminationpaper.entity.AchExaminationPaper;
import org.jeecg.modules.achexaminationpaper.mapper.AchExaminationPaperMapper;
import org.jeecg.modules.achexaminationpaper.service.IAchExaminationPaperService;
import org.jeecg.modules.achexaminationpaper.vo.AchExaminationPaperVo;
import org.jeecg.modules.achexampaperprojectitem.entity.AchExamPaperProjectItem;
import org.jeecg.modules.achexampaperprojectitem.service.IAchExamPaperProjectItemService;
import org.jeecg.modules.relation.relachstandarddistribution.entity.RelAchStandardDistribution;
import org.jeecg.modules.relation.relachstandarddistribution.service.IRelAchStandardDistributionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: ach_examination_paper
 * @author: baochangrong
 * @Date: 2022-03-15
 * @Version: V1.0
 */
@Service
public class AchExaminationPaperServiceImpl extends ServiceImpl<AchExaminationPaperMapper, AchExaminationPaper> implements IAchExaminationPaperService {

    @Autowired
    AchExaminationPaperMapper achExaminationPaperMapper;

//    @Autowired
//    private IAchExaminationPaperService achExaminationPaperService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    /**
     * 试卷分项
     */
    @Autowired
    private IAchExamPaperProjectItemService achExamPaperProjectItemService;
    /**
     * 标准
     */
    @Autowired
    private IAchAchievementStandardService achAchievementStandardService;
    /**
     * 试卷 标准关系
     */
    @Autowired
    private IRelAchStandardDistributionService relAchStandardDistributionService;
    /**
     * 标准明细
     */
    @Autowired
    private IAchAchieveStandardItemService achAchieveStandardItemService;

    /**
     * 查询全部考试试卷 分页查询
     */
    @Override
    public IPage<AchExaminationPaperVo> getAchExaminationPaperList(Page<AchExaminationPaperVo> page, @Param("AchExaminationPaperVo") AchExaminationPaperVo achExaminationPaperVo) {
        List<AchExaminationPaperVo> achExaminationPaperList = achExaminationPaperMapper.getAchExaminationPaperList(page, achExaminationPaperVo);
        return page.setRecords(achExaminationPaperList);
    }

    @Override
    public List<AchExaminationPaper> queryAllByExamId(String examId) {
        QueryWrapper<AchExaminationPaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("examination_id", examId)
                .eq("del_flag", 0);
        List<AchExaminationPaper> list = list(queryWrapper);
        return list;
    }

    @Override
    public Result<?> copyAchExaminationPaper(AchExaminationPaper oldAchExaminationPaper) {
        //查询要复制的试卷
        AchExaminationPaper newAchExaminationPaper = getById(oldAchExaminationPaper.getId());
        //参数（@RequestBody oldAchExaminationPaper）中，必须要有：id（为旧试卷id），自定义的新试卷编码、新试卷名称、新试卷所属考试、新试卷类型的值。
        newAchExaminationPaper.setExaminationPaperCode(oldAchExaminationPaper.getExaminationPaperCode());//新试卷编码
        newAchExaminationPaper.setExaminationPaperName(oldAchExaminationPaper.getExaminationPaperName());//新试卷名称
        newAchExaminationPaper.setExaminationId(oldAchExaminationPaper.getExaminationId());//新试卷所属所属考试
        newAchExaminationPaper.setExaminationPaperTtype(oldAchExaminationPaper.getExaminationPaperTtype());//新试卷类型
        //将要复制的模板试卷信息以新的试卷信息插入
		String oldExaminationPaperId = oldAchExaminationPaper.getId(); //提取模板试卷id
        newAchExaminationPaper.setId(null); //清空模板试卷id
        newAchExaminationPaper.setCreateTime(null); //创建时间

        //及时返回新数据id
        save(newAchExaminationPaper); //内置save方法执行后，后续的使用自动存在新记录的id
        //查询模板试卷标准
        //替换标准关联的试卷id，清空标准id并以新试卷标准存入数据库

        Map<String, String> old2newPaperProjectItemMap = new HashMap<String, String>(); //定义点试卷分项结构的id对应关系
        //通过模板试卷id查询模板试卷子项信息（子项有多个）
        QueryWrapper<AchExamPaperProjectItem> wrapper = new QueryWrapper<>();
        wrapper.likeRight("examination_paper_id", oldAchExaminationPaper.getId());
        List<AchExamPaperProjectItem> oldAchExamPaperProjectItemList = achExamPaperProjectItemService.list(wrapper);
        for (AchExamPaperProjectItem oldAchExamPaperProjectItem : oldAchExamPaperProjectItemList) {

            //复制试卷分项结构
            String oldAchExamPaperProjectItemJSON = JSONObject.toJSONString(oldAchExamPaperProjectItem);
            AchExamPaperProjectItem newAchExamPaperProjectItem = JSONObject.parseObject(oldAchExamPaperProjectItemJSON, AchExamPaperProjectItem.class);
//			AchExamPaperProjectItem newAchExamPaperProjectItem = oldAchExamPaperProjectItem; //直接用旧的分项结构定义新的分项
            newAchExamPaperProjectItem.setId("");
            newAchExamPaperProjectItem.setExaminationPaperId(newAchExaminationPaper.getId());//重新定义分项的试卷id，将新的试卷ID赋值给新的分项的试卷id
            newAchExamPaperProjectItem.setCreateTime(null);  //创建时间
            achExamPaperProjectItemService.save(newAchExamPaperProjectItem);//保存，立即返回id 后续就带有生成的id

            //保存新旧id对应关系：试卷分项结构的id对应关系
            old2newPaperProjectItemMap.put(oldAchExamPaperProjectItem.getId(), newAchExamPaperProjectItem.getId());

        }

        //拿到试卷标准分配关系
        RelAchStandardDistribution relAchStandardDistribution = new RelAchStandardDistribution();
        relAchStandardDistribution.setRelObjId(oldAchExaminationPaper.getId());
        List<RelAchStandardDistribution> oldRelAchStandardDistributionList = relAchStandardDistributionService.list(new QueryWrapper<RelAchStandardDistribution>(relAchStandardDistribution));
        //存在多值情况 遍历list中的标准id依次查询对应的标准
        for (RelAchStandardDistribution oldRelAchStandDistribution : oldRelAchStandardDistributionList) {
            //复制标准
            AchAchievementStandard oldAchAchievementStandard = achAchievementStandardService.getById(oldRelAchStandDistribution.getAchievementStandardId());
            String oldAchAchievementStandardJSON = JSONObject.toJSONString(oldAchAchievementStandard);
            AchAchievementStandard newAchAchievementStandard = JSONObject.parseObject(oldAchAchievementStandardJSON, AchAchievementStandard.class);
            newAchAchievementStandard.setId(null);
            newAchAchievementStandard.setAchievementStandardName(newAchExaminationPaper.getExaminationPaperName() + "评分标准");
            newAchAchievementStandard.setCreateTime(null);
            newAchAchievementStandard.setAchievementStandardPurpose("12");//应用类型：12应用于试卷的标准
            boolean saveAchAchiStandard = achAchievementStandardService.save(newAchAchievementStandard); //后续实体附带新数据id
            if (saveAchAchiStandard) {
            } else {
                return Result.error("试卷生成完成，标准生成出错，请检查数据");
            }
            //标准保存完毕
            //复制标准明细
            AchAchieveStandardItem achAchieveStandardItem = new AchAchieveStandardItem();
            achAchieveStandardItem.setAchievementStandardId(oldAchAchievementStandard.getId());//设置参数
            QueryWrapper<AchAchieveStandardItem> queryWrapper = QueryGenerator.initQueryWrapper(achAchieveStandardItem, null);

            List<AchAchieveStandardItem> oldAchAchieveStandardItemList = achAchieveStandardItemService.list(queryWrapper);

            for (AchAchieveStandardItem oldAchAchieveStandardItem : oldAchAchieveStandardItemList) {
                String oldAchAchieveStandardItemJSON = JSONObject.toJSONString(oldAchAchieveStandardItem);
                AchAchieveStandardItem newAchAchieveStandardItem = JSONObject.parseObject(oldAchAchieveStandardItemJSON, AchAchieveStandardItem.class);
                newAchAchieveStandardItem.setId(null);
                //根据是否为总分（试卷）标准项做判断处理
                if (oldAchAchieveStandardItem.getExaPapProItemCode().equals(oldExaminationPaperId)) {
                    //如果是总分项标准，set设置新试卷的id
                    newAchAchieveStandardItem.setExaPapProItemCode(newAchExaminationPaper.getId());
                } else {
                    //如果是试卷分享标准，set设置新的试卷分项id
                    newAchAchieveStandardItem.setExaPapProItemCode(old2newPaperProjectItemMap.get(oldAchAchieveStandardItem.getExaPapProItemCode()));
                }
                newAchAchieveStandardItem.setAchievementStandardId(newAchAchievementStandard.getId());
//				newAchAchieveStandardItem.setStandItemFatherId(); //设置父级id，暂不实现，以后补充
                newAchAchieveStandardItem.setCreateTime(null);
                achAchieveStandardItemService.save(newAchAchieveStandardItem);
            }
            //标准明细复制完毕

            //复制关系
            String oldRelAchStandDistributionJSON = JSONObject.toJSONString(oldRelAchStandDistribution);
            RelAchStandardDistribution newRelAchStandardDistribution = JSONObject.parseObject(oldRelAchStandDistributionJSON, RelAchStandardDistribution.class);
            newRelAchStandardDistribution.setId(null);
            newRelAchStandardDistribution.setRelObjId(newAchExaminationPaper.getId());
            newRelAchStandardDistribution.setAchievementStandardId(newAchAchievementStandard.getId());
            newRelAchStandardDistribution.setCreateTime(null);
            newRelAchStandardDistribution.setRelObjType("1");
            relAchStandardDistributionService.save(newRelAchStandardDistribution);
        }
        return Result.OK("复制成功");
    }

}
